function checkDoc (buffer) {
  if (!buffer.length) {
    return true
  }
  let num0, num1 = buffer[0], num2 = 32
  for (let i = 1, len = buffer.length; i < len; i++) {
    num0 = num1
    num1 = num2
    num2 = buffer[i]
    if (!checkAll(num0, num1, num2)) {
      return false
    }
  }
  let result
  num0 = num1
  num1 = num2
  num2 = 32
  result = checkAll(num0, num1, num2)
  return result
}

function checkGbkFile (buffer) {
  if (!buffer.length) {
    return true
  }
  let num0, num1 = buffer[0], num2 = 32
  for (let i = 1, len = buffer.length; i < len; i++) {
    num0 = num1
    num1 = num2
    num2 = buffer[i]
    if (!checkGbk(num0, num1, num2)) {
      return false
    }
  }
  let result
  num0 = num1
  num1 = num2
  num2 = 32
  result = checkGbk(num0, num1, num2)
  return result
}

function checkAll (num0, num1, num2) {
  if (!checkGbk(num0, num1, num2)) {
    if (!checkUtf(num0, num1, num2)) {
      return false
    } else {
      return true
    }
  } else {
    return true
  }
}

/**
 * 检查是否是gbk编码
 */
function checkGbk (num0, num1, num2) {
  let maxNum = 160
  if (num1 > 127 && num1 < 160) {
    return false
  }
  return checkUtf(num0, num1, num2, maxNum)
}

/**
 * 检查是否是utf-8编码
 */
function checkUtf (num0, num1, num2, max) {
  let maxNum = (typeof max === 'undefined' ? 128 : max)
  if (num1 < 32 && !num1 === 9 && !num1 === 10) {
    if (num1 === 13 && num2 === 10) {
      return true
    }
    return false
  } else if (num1 >= maxNum) {
    if (num2 >= maxNum || num0 >= maxNum) {
      return true
    }
    return false
  }
  return true
}

module.exports = {
  checkDoc,
  checkGbkFile
}
